package cn.yunyichina.reservation.controller.console;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yunyichina.reservation.constant.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.yunyichina.provider.framework.dubbo.service.ReservationService;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.reservation.common.ResponseEnum;
import cn.yunyichina.reservation.common.jackson.Jackson;
import cn.yunyichina.reservation.controller.BaseController;
import cn.yunyichina.reservation.util.HttpUtil;
import cn.yunyichina.reservation.util.PasswordUtil;
import cn.yunyichina.reservation.vo.ConsoleUserVo;

/**
 * 登录控制器
 * Created by Lullaby on 2016/8/18.
 */
@RestController
@RequestMapping("console")
public class ConsoleLoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ConsoleLoginController.class);

    /* 获取后台管理员用户 */
    private static final String RESERVATION_CONSOLE_USER_GET = "yyt.reservation.console.user.get";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录接口生成会话
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("login")
    public HttpResponse login(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        HttpResponse httpResponse = new HttpResponse();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            Map<String, String> params = new HashMap<>();
            params.put("username", username);
            Response serviceResponse = ReservationService.callHumpFromInternal(
                    RESERVATION_CONSOLE_USER_GET, Jackson.getBaseJsonData(params)
            );
            if (serviceResponse == null) {
                return httpResponse.failure(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMessage());
            }
            if (Interface.SUCCESS.equals(serviceResponse.getResultCode())) {
                String result = serviceResponse.getResult();
                ConsoleUserVo user = Jackson.getBeanJsonData(result, ConsoleUserVo.class);
                if (user != null) {
                    if (PasswordUtil.verify(password, user.getPassword())) {
                        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
                        stringStringValueOperations.set(
                                Redis.CONSOLE_SESSION_PREFIX.concat(user.getUsername()),
                                result, Redis.CONSOLE_SESSION_TIMEOUT, TimeUnit.SECONDS);
                        Cookie cookie = new Cookie(
                                Console.CONSOLE_COOKIE_NAME, Base64.encodeBase64String(username.getBytes(Encoding.UTF8))
                        );
                        response.addCookie(cookie);
                        httpResponse.success(ResponseEnum.LOGIN_SUCCESS.getMessage());
                    } else {
                        httpResponse.failure(
                                ResponseEnum.WRONG_USERNAME_PASSWORD.getCode(),
                                ResponseEnum.WRONG_USERNAME_PASSWORD.getMessage()
                        );
                    }
                } else {
                    httpResponse.failure(
                            ResponseEnum.USER_NOT_EXIST.getCode(),
                            ResponseEnum.USER_NOT_EXIST.getMessage()
                    );
                }
            } else {
                httpResponse.failure(serviceResponse.getResultCode(), serviceResponse.getResultMessage());
            }
        } else {
            httpResponse.failure(
                    ResponseEnum.EMPTY_USERNAME_PASSWORD.getCode(),
                    ResponseEnum.EMPTY_USERNAME_PASSWORD.getMessage()
            );
        }
        return httpResponse;
    }

    @RequestMapping("logout")
    public HttpResponse logout(HttpServletRequest request, HttpServletResponse response) {
        HttpResponse httpResponse = new HttpResponse();
        String username = (String) request.getAttribute(Console.USERNAME);
        stringRedisTemplate.delete(Redis.CONSOLE_SESSION_PREFIX.concat(username));
        HttpUtil.deleteCookie(response, Console.CONSOLE_COOKIE_NAME);
        return httpResponse.success(ResponseEnum.LOGOUT_SUCCESS.getMessage());
    }

    @RequestMapping(value = "test")
    public String test() {
        logger.info("[ LoginController -> /console/test ]");
        return "Hello, world!";
    }

}
